﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.Core.Support;
using System.Collections.Generic;

namespace MS.InformationManagement.Documents.ObjectDef.Lists.PerfilesListDefinition.PerfilesEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class PerfilesEventReceiver : SPItemEventReceiver
    {
       /// <summary>
       /// An item is being updated.
       /// </summary>
        public override void ItemUpdating(SPItemEventProperties properties)
       {
           base.ItemUpdating(properties);
           if (properties.List.Title.Equals("Perfiles"))
               try
               {
                   this.EventFiringEnabled = false;
                   string oldPerfilName = properties.ListItem["Perfil_User"].ToString();
                   string newPerfilName = properties.AfterProperties["Perfil_User"].ToString();
                   using (SPSite currentSite = properties.OpenSite())
                   {
                       UpdateUserDependencies(oldPerfilName, newPerfilName, currentSite);
                   }
               }
               catch (Exception ex)
               {
                   Logger.LogException(ex, Microsoft.SharePoint.Administration.EventSeverity.Error,
                           SPDiagnosticsAreas.SHAREPOINTFOUNDATION, SPDiagnosticsAreas.SharepointFoundationDiagnosticsCategories.WEBPARTS);
               }
                finally
                {
                    this.EventFiringEnabled = true;
                }

       }

       private static void UpdateUserDependencies(string oldPerfilName, string newPerfilName, SPSite site)
       {
           Dictionary<string, string> userDictionary = PeopleHelper.GetUsersByProperty(GlobalConstants.UP_USER_PERFIL, oldPerfilName, true, site);
           foreach (KeyValuePair<string, string> user in userDictionary)
           {
               PeopleHelper.UpdatePropertyUserProfile(GlobalConstants.UP_USER_PERFIL, newPerfilName, user.Key, site);
           }
       }
    }
}
